using System.IO;
using System.Collections.Generic;
using System.Configuration;

namespace mock_ehr_lib.Data.LookupServices
{
    public class ICD9LookupService : ILookupService
    {
        private static readonly Dictionary<string, string> Lookups;
        private readonly string _filename;
        private static ICD9LookupService _instance;

        static ICD9LookupService()
        {
            Lookups = new Dictionary<string, string>();
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="filename">A text file containing the ICD9 lookups</param>
        private ICD9LookupService()
        {
            string filename = ConfigurationManager.AppSettings["icd9Filename"];
            var lines = File.ReadLines(filename);
            foreach(var line in lines)
            {
                var firstSpaceIndex = line.IndexOf("\t");
                var code = line.Substring(0, firstSpaceIndex);
                var description = line.Substring(firstSpaceIndex + 1);
                Lookups.Add(code, description);
            }
        }

        public static ICD9LookupService Instance
        {
            get
            {
                return _instance ?? (_instance = new ICD9LookupService());
            }
        }

        public string GetDescriptionByCode(string code)
        {
            return Lookups[code.Replace(".", "")];
        }
    }
}